<template>
  <div class="blockchain-browser-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>区块链社保交易记录查询</h2>
      <p class="subtitle">查询您的社保交易在区块链上的记录和状态</p>
    </div>

    <!-- 查询表单 -->
    <el-card class="query-card">
      <template #header>
        <div class="card-header">
          <h3>查询条件</h3>
        </div>
      </template>
      
      <el-form :model="queryForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号码">
              <el-input v-model="queryForm.idNumber" placeholder="请输入身份证号码" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易类型">
              <el-select v-model="queryForm.transactionType" placeholder="请选择交易类型" clearable style="width: 100%">
                <el-option label="缴纳社保" value="payment"></el-option>
                <el-option label="社保转移" value="transfer"></el-option>
                <el-option label="社保理赔" value="claim"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期">
              <el-date-picker v-model="queryForm.startDate" type="date" placeholder="选择开始日期" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期">
              <el-date-picker v-model="queryForm.endDate" type="date" placeholder="选择结束日期" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="searchTransactions">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 交易记录列表 -->
    <el-card class="transaction-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>交易记录</h3>
        </div>
      </template>
      
      <el-table :data="transactionList" style="width: 100%" border>
        <el-table-column prop="txHash" label="交易哈希" width="220">
          <template #default="scope">
            <el-tooltip :content="scope.row.txHash" placement="top" effect="light">
              <span class="hash-text">{{ truncateHash(scope.row.txHash) }}</span>
            </el-tooltip>
            <el-button link type="primary" size="small" @click="copyToClipboard(scope.row.txHash)">
              <i class="el-icon-document-copy"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="timestamp" label="交易时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="交易类型" width="120">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ getTransactionTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="150">
          <template #default="scope">
            ¥ {{ scope.row.amount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'confirmed' ? 'success' : 'warning'">
              {{ scope.row.status === 'confirmed' ? '已确认' : '处理中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="viewTransactionDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="交易详情"
      width="700px"
    >
      <div v-if="currentTransaction" class="transaction-details">
        <div class="detail-item">
          <span class="label">交易哈希：</span>
          <span class="value hash-value">
            {{ currentTransaction.txHash }}
            <el-button link type="primary" size="small" @click="copyToClipboard(currentTransaction.txHash)">
              <i class="el-icon-document-copy"></i>
            </el-button>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">区块高度：</span>
          <span class="value">{{ currentTransaction.blockNumber }}</span>
        </div>
        <div class="detail-item">
          <span class="label">交易时间：</span>
          <span class="value">{{ formatDate(currentTransaction.timestamp) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">交易类型：</span>
          <span class="value">
            <el-tag :type="getTagType(currentTransaction.type)">
              {{ getTransactionTypeName(currentTransaction.type) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">交易金额：</span>
          <span class="value">¥ {{ currentTransaction.amount.toLocaleString() }}</span>
        </div>
        <div class="detail-item">
          <span class="label">发送方：</span>
          <span class="value address-value">{{ currentTransaction.from }}</span>
        </div>
        <div class="detail-item">
          <span class="label">接收方：</span>
          <span class="value address-value">{{ currentTransaction.to }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <span class="value">
            <el-tag :type="currentTransaction.status === 'confirmed' ? 'success' : 'warning'">
              {{ currentTransaction.status === 'confirmed' ? '已确认' : '处理中' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item" v-if="currentTransaction.description">
          <span class="label">交易说明：</span>
          <span class="value">{{ currentTransaction.description }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import axios from 'axios';

// 查询表单数据
const queryForm = reactive({
  idNumber: '',
  transactionType: '',
  startDate: '',
  endDate: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 交易列表数据
const transactionList = ref([]);
const loading = ref(false);

// 交易详情相关
const dialogVisible = ref(false);
const currentTransaction = ref(null);

// 模拟获取交易数据
const searchTransactions = async () => {
  loading.value = true;
  try {
    // 这里应该是实际的API调用，现在用模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟数据
    const mockData = [];
    for (let i = 0; i < 20; i++) {
      const type = ['payment', 'transfer', 'claim'][Math.floor(Math.random() * 3)];
      mockData.push({
        txHash: `0x${Math.random().toString(16).substr(2, 40)}`,
        blockNumber: Math.floor(Math.random() * 1000000) + 15000000,
        timestamp: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
        type,
        amount: Math.floor(Math.random() * 10000) + 100,
        status: Math.random() > 0.2 ? 'confirmed' : 'pending',
        from: `0x${Math.random().toString(16).substr(2, 40)}`,
        to: `0x${Math.random().toString(16).substr(2, 40)}`,
        description: type === 'payment' ? '社保缴费' : 
                    type === 'transfer' ? '社保转移' : '社保理赔'
      });
    }
    
    transactionList.value = mockData;
    total.value = 100; // 模拟总数
    
    ElNotification({
      title: '查询成功',
      message: '已获取区块链交易记录',
      type: 'success'
    });
  } catch (error) {
    console.error('获取交易记录失败:', error);
    ElNotification({
      title: '查询失败',
      message: '获取区块链交易记录失败，请稍后重试',
      type: 'error'
    });
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = '';
  });
  currentPage.value = 1;
  searchTransactions();
};

// 查看交易详情
const viewTransactionDetails = (transaction) => {
  currentTransaction.value = transaction;
  dialogVisible.value = true;
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
};

// 截断哈希值显示
const truncateHash = (hash) => {
  if (!hash) return '';
  return `${hash.substring(0, 8)}...${hash.substring(hash.length - 8)}`;
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage({
      message: '已复制到剪贴板',
      type: 'success'
    });
  }).catch(() => {
    ElMessage({
      message: '复制失败，请手动复制',
      type: 'error'
    });
  });
};

// 获取交易类型标签样式
const getTagType = (type) => {
  switch (type) {
    case 'payment': return 'primary';
    case 'transfer': return 'success';
    case 'claim': return 'warning';
    default: return 'info';
  }
};

// 获取交易类型名称
const getTransactionTypeName = (type) => {
  switch (type) {
    case 'payment': return '缴纳社保';
    case 'transfer': return '社保转移';
    case 'claim': return '社保理赔';
    default: return '未知类型';
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  searchTransactions();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  searchTransactions();
};

// 页面加载时获取数据
onMounted(() => {
  searchTransactions();
});
</script>

<style scoped>
.blockchain-browser-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.subtitle {
  color: #606266;
  margin-top: 8px;
}

.query-card,
.transaction-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hash-text {
  font-family: monospace;
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.transaction-details {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-item .label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}

.detail-item .value {
  flex: 1;
}

.hash-value,
.address-value {
  font-family: monospace;
  word-break: break-all;
}
</style>